package com.codeoss.framework.workflow.parser;

import org.springframework.stereotype.Service;

import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.ExpressionUtil;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.workflow.def.DecisionNodeDef;
import com.codeoss.framework.workflow.def.WorkflowElementDef;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service
public class DecisionNodeParser  implements IWorkflowElementParser{

	@Override
	public WorkflowElementDef parse(IWorkflowElementParseContext workflowElementParseContext, ObjectNode objectNode) {
		// TODO Auto-generated method stub
		DecisionNodeDef decisionNode=new DecisionNodeDef();
		JsonNode jsonNode=objectNode.get("name");
		if(jsonNode!=null) {
			decisionNode.setName(jsonNode.asText());
		}
		jsonNode=objectNode.get("decisionExpression");
		if(jsonNode!=null) {
			String decisionExpression=jsonNode.asText();
			if(!StringUtils.isEmpty(decisionExpression) && !"null".equals(decisionExpression)) {
				Expression expression=ExpressionUtil.convertToExpression(decisionExpression, Expression.EXPRESSION_TYPE_JAVASCRIPT);
				decisionNode.setDecisionExpression(expression);
			}
		}
		
		
		jsonNode=objectNode.get("startEventExpression");
		if(jsonNode!=null) {
			String startEventExpression=jsonNode.asText();
			if(!StringUtils.isEmpty(startEventExpression) && !"null".equals(startEventExpression)) {
				Expression expression=ExpressionUtil.convertToExpression(startEventExpression, Expression.EXPRESSION_TYPE_JAVASCRIPT);
				decisionNode.setStartEventExpression(expression);
			}
		}
		
		jsonNode=objectNode.get("endEventExpression");
		if(jsonNode!=null) {
			String endEventExpression=jsonNode.asText();
			if(!StringUtils.isEmpty(endEventExpression) && !"null".equals(endEventExpression)) {
				Expression expression=ExpressionUtil.convertToExpression(endEventExpression, Expression.EXPRESSION_TYPE_JAVASCRIPT);
				decisionNode.setEndEventExpression(expression);
			}
		}
		
		jsonNode=objectNode.get("id");
		if(jsonNode!=null) {
			decisionNode.setId(jsonNode.asText());
		}
		return decisionNode;
	}

}
